<template>
    <div class="app-container" v-loading="loading">
        <div class="add-row-center-box">
            <el-form ref="form" v-if="handleType !== handleEnum.detail" :model="form" inline :rules="rules"
                     label-position="top" class="form-item-column column-2">
                <div>
                    <el-form-item label="物料图片" prop="productImage">
                        <ImageUpload v-model="form.productImage" :limit="1" :file-size="0" :is-show-tip="false"/>
                    </el-form-item>
                </div>
                <el-form-item label="物料名称" prop="productName">
                    <el-input v-model="form.productName" size="small" placeholder="请输入物料名称"/>
                </el-form-item>
                <el-form-item label="物料编号" prop="productNo">
                    <el-input v-model="form.productNo" size="small" placeholder="请输入物料名称"/>
                </el-form-item>
                <el-form-item label="客户" prop="productCustomer">
                    <el-input v-model="form.productCustomer" size="small" placeholder="请输入客户"/>
                </el-form-item>
                <el-form-item label="所属分类" prop="productCategory">
                    <el-select v-model="productCategoryLabel" size="small" :disabled="editFlag" placeholder="请选择分类" filterable clearable
                               @change="onCategoryChange">
                       <!-- <el-option v-for="item in category" :label="item.categoryName" :value="item.categoryId"/> -->
                        <el-option v-for="item in category" :label="item.categoryName" :value="item"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="二级分类" prop="subCategory">
                    <el-select v-model="subCategory" size="small" placeholder="请选择二级分类" :disabled="editFlag" filterable clearable>
                        <el-option v-for="item in subCategoryList" :value="item.categoryId" :label="item.categoryName"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="批次号" prop="productBatchNo">
                    <el-input v-model="form.productBatchNo" size="small" placeholder="请输入批次号"/>
                </el-form-item>
                <el-form-item label="规格" prop="productSku">
                    <el-input v-model="form.productSku" size="small" placeholder="请输入规格"/>
                </el-form-item>
                <el-form-item label="颜色" prop="productColour">
                    <el-input v-model="form.productColour" size="small" placeholder="请输入颜色"/>
                </el-form-item>
                <el-form-item label="库存" prop="productStock">
                    <el-input v-model.number="form.productStock" size="small" placeholder="请输入库存"/>
                    <el-checkbox class="form-sub-bottom" v-model="form.productNegative" label="允许负库存"
                                 :true-label="negativeEnum.allow" :false-label="negativeEnum.notAllow"/>
                </el-form-item>
                <el-form-item label="库存预警" prop="productStockWarning">
                    <el-input v-model.number="form.productStockWarning" size="small" placeholder="请输入库存预警"/>
                </el-form-item>
                <el-form-item label="供应商" prop="productSupplier" v-if="typeFlag==2||typeFlag==3||productCategoryLabel=='原材料'||productCategoryLabel=='其他'">
                    <el-input v-model.number="form.productSupplier" size="small" placeholder="请输入供应商"/>
                </el-form-item>



                <!--增行表格-->
                <div class="form-table" v-if="typeFlag=='0'||typeFlag=='1'">
                    <el-form-item label="生产所需" prop="needVoList" style="width: 100%">
                        <label slot="label" class="el-form-item__label">生产所需
                            <el-button type="text" size="mini" icon="el-icon-plus" @click="onAddRow">增行
                            </el-button>
                        </label>
                        <el-table :data="form.needVoList" v-loading="tableLoading">
                            <el-table-column label="物料编号" prop="productNo">
                                <el-form-item slot-scope="{row, $index}" label="" :rules="rules.productNo"
                                              :prop="'needVoList.'+$index+'.productNo'">
                                    <el-input v-model="row.productNo" size="mini" placeholder="请输入物料编号"
                                              @keyup.enter.native="(e) => checkProduceNeed(row)"
                                              @blur="(e) => checkProduceNeed(row)"/>
                                </el-form-item>
                            </el-table-column>
                            <el-table-column label="物料名称" prop="productName"/>
                            <el-table-column label="数量" prop="productNum">
                                <el-form-item slot-scope="{row, $index}" label="" :rules="rules.num"
                                              :prop="'needVoList.'+$index+'.productNum'">
                                    <el-input v-model.number="row.productNum" size="mini" placeholder="请输入数量"
                                              :disabled="!row.productName"/>
                                </el-form-item>
                            </el-table-column>
                            <el-table-column v-if="!editFlag" width="50" class-name="small-padding">
                                <el-button slot-scope="{row, $index}" size="mini" type="text"
                                           @click="onDeleteNeed($index)">
                                    删除
                                </el-button>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </div>
            </el-form>

            <detail v-else :data="detail" :category-list="category"/>
            <div class="footer">
                <el-button v-if="handleType === handleEnum.detail" size="small" @click="cancel">返 回</el-button>
                <el-button v-if="handleType === handleEnum.add|| handleType === handleEnum.edit" size="small" @click="cancel">取 消</el-button>
                <el-button v-if="handleType === handleEnum.add|| handleType === handleEnum.edit" type="primary" size="small" @click="submitForm">
                    确 定
                </el-button>
            </div>
        </div>
    </div>

</template>

<script>
import {categoryNeedEnum, handleEnum, negativeEnum, responseEnum} from "../../../const/const";
import ImageUpload from "@/components/ImageUpload/"
import {INTEGER, IS_INTEGER} from "../../../utils/validate";
import {getMaterialDetail, getProductInfo} from "./api";
import Api from "./api";
import _ from "lodash";
import {getCategoryList} from "../category/api";
import detail from "./detail";

export default {
     name: "materialAdd",
    components: {ImageUpload, detail},
    data() {
        return {
            editFlag:false,
            loading: false,
            // 操作枚举
            handleEnum,
            IS_INTEGER,
            // 允许负库存枚举
            negativeEnum,
            // 表格loading
            tableLoading: false,

            handleType: null,

            productCategoryLabel:'',//分类名称
            form: {
                productNo:null, // 物料编号
                productName: null,  // 物料名称
                productImage: '',  // 图片地址
                productCategory: null,  // 分类Id
                productCustomer: null, // 客户
                productBatchNo: null, // 批次号
                productColour: null,  // 颜色
                productSku: null,  // 规格
                productStock: 0,// 库存
                productStockWarning: 0,// 库存预警
                productNegative: negativeEnum.notAllow,// 允许负库存（0允许 1不允许）
                productSupplier:null,//供应商
                needVoList: [{ // 生产所需
                    productName: null, // 物料名称
                    productNo: null, // 物料编号
                    productNum: null // 数量
                }]
            },
            // 校验
            // rules: {
            //     productName: [{required: true, message: '请输入物料名称'}],
            //     productImage: [{required: true, message: '请上传图片'}],
            //     productCategory: [{required: true, message: '请选择分类'}],
            //     productBatchNo: [{required: true, message: '请输入批次号'}],
            //     productSku: [{required: true, message: '请输入规格'}],
            //     productColour: [{required: true, message: '请输入颜色'}],
            //     productCustomer: [{required: true, message: '请输入客户'}],
            //     productStock: [
            //         {required: true, message: '请输入库存'},
            //         {
            //             validator: (rule, value, callback) => {
            //                 if (this.form.productNegative === negativeEnum.allow && !INTEGER.test(value)) {
            //                     callback(new Error('请输入整数'));
            //                 } else if (this.form.productNegative === negativeEnum.notAllow && !IS_INTEGER.test(value)) {
            //                     callback(new Error('请输入正整数'));
            //                 } else {
            //                     callback();
            //                 }
            //             }
            //         }],
            //     productStockWarning: [{pattern: IS_INTEGER, message: '请输入正整数'}],
            //     needVoList: [{required: true, message: '请填写物料信息'}],
            //     num: [{required: true, pattern: IS_INTEGER, message: '请输入正整数'}]
            // },
    rules: {
          productNo: [{required: true, message: '请输入物料编号'}],
            productName: [{required: false, message: '请输入物料名称'}],
            productImage: [{required: false, message: '请上传图片'}],
            productCategory: [{required: false, message: '请选择分类'}],
            productBatchNo: [{required: false, message: '请输入批次号'}],
            productSku: [{required: false, message: '请输入规格'}],
            productColour: [{required: false, message: '请输入颜色'}],
            productCustomer: [{required: false, message: '请输入客户'}],
            productStock: [
                {required: false, message: '请输入库存'},
                {
                    validator: (rule, value, callback) => {
                        if (this.form.productNegative === negativeEnum.allow && !INTEGER.test(value)) {
                            callback(new Error('请输入整数'));
                        } else if (this.form.productNegative === negativeEnum.notAllow && !IS_INTEGER.test(value)) {
                            callback(new Error('请输入正整数'));
                        } else {
                            callback();
                        }
                    }
                }],
            productStockWarning: [{pattern: IS_INTEGER, message: '请输入正整数'}],
            needVoList: [{required: false, message: '请填写物料信息'}],
            num: [{required: false, pattern: IS_INTEGER, message: '请输入正整数'}]
        },

            typeFlag:0,
            // 一级分类
            category: [],
            // 二级分类
            subCategoryList: [],
            subCategory: null,
            // 平铺一份分类数据
            flatCategory: [],

            // 存起输入框的值，避免重复查询
            tempInput: null,

            // 详情数据
            detail: {},
            //物料id
            productId:null
        }
    },
    computed: {
        isNeed() {
            const category = this.form.productCategory;
            return this.flatCategory.some(so => so.categoryId === category && so.categoryNeed === categoryNeedEnum.yes);
        }
    },
    mounted() {
        this.handleType = this.$route.query.handleType
        if(this.handleType=='edit'){
            this.editFlag=true
        }
        this.productId= this.$route.query.productId
        // 查询物料分类
        this.getCategory();
    },
    methods: {
        /** 查询物料分类 */
        getCategory() {
            getCategoryList().then(res => {
                if (res.code === responseEnum.success) {
                    this.category = res.rows || [];
                    // 平铺一份数据
                    res.rows.forEach(item => {
                        this.flatCategory.push(item);
                        item.children && item.children.forEach(child => {
                            this.flatCategory.push(child);
                        })
                    })
                    // 有id才查详情
                    if(this.productId){
                        this.getDetail(this.productId);
                    }
                }
            });
        },
        /**
         * 查询详情
         */
        getDetail(productId) {
            this.loading = true
            getMaterialDetail(productId).then(res => {
                if (res.code === responseEnum.success) {
                    this.detail=res.data;
                     this.form.productName=res.data.productName||null; // 物料名称
                      this.form.productNo=res.data.productNo||null; // 物料编号
                     this.form.productImage= res.data.productImage||null; // 图片地址
                     this.form.productCategory=res.data.categoryId||null;// 分类Id
                     this.productCategoryLabel=res.data.productChildCategory||null;// 分类名称
                     if(this.productCategoryLabel=='成品'){
                         this.typeFlag=0
                         this.rules.productName[0].required=true
                         this.rules.productCustomer[0].required=true
                           this.rules.productCategory[0].required=true
                            this.rules.productStock[0].required=true
                             this.rules.productBatchNo[0].required=false
                     }
                     if(this.productCategoryLabel=='半成品'){
                          this.typeFlag=1
                          this.rules.productName[0].required=true
                          this.rules.productCategory[0].required=true
                         this.rules.productStock[0].required=true
                          this.rules.productCustomer[0].required=false
                           this.rules.productBatchNo[0].required=false
                     }
                     if(this.productCategoryLabel=='原材料'){
                         this.typeFlag=2
                         this.rules.productName[0].required=true
                         this.rules.productBatchNo[0].required=false
                          this.rules.productCustomer[0].required=false
                          this.rules.productStock[0].required=true
                          this.rules.productCategory[0].required=false
                     }if(this.productCategoryLabel=='其他'){
                     this.typeFlag=3
                      this.rules.productName[0].required=false
                        this.rules.productCustomer[0].required=false
                        this.rules.productCategory[0].required=false
                         this.rules.productStock[0].required=false
                         this.rules.productBatchNo[0].required=false
                     }
                     this.form.productCustomer=res.data.productCustomer||null;// 客户
                     this.form.productBatchNo=res.data.productBatchNo||null; // 批次号
                     this.form.productColour=res.data.productColour||null;  // 颜色
                    this.form.productSupplier=res.data.productSupplier||null // 供应商
                    this.form.productSku=res.data.productSku||null; // 规格
                     this.form.productStock=res.data.productStock||0;// 库存
                     this.form.productStockWarning=res.data.productStockWarning||0;// 库存预警
                     this.form.productNegative=res.data.productNegative||0;//允许负库存（0允许 1不允许）
                     this.form.needVoList=res.data.needsList||[];

                    // 查找二级分类
                    this.subCategoryList = this.category.find(item=> item.categoryId === res.data.categoryId).children;
                    this.subCategory = res.data.categoryParentId;
                    this.detail = res.data
                }
            }).finally(() => this.loading = false)
        },
        /**
         * 切换一级分类
         */
        onCategoryChange(val) {
            if(val.categoryName=='成品'){
                this.typeFlag=0
                this.rules.productName[0].required=true
                this.rules.productCustomer[0].required=true
                  this.rules.productCategory[0].required=true
                   this.rules.productStock[0].required=true
                    this.rules.productBatchNo[0].required=false
            }
            if(val.categoryName=='半成品'){
                 this.typeFlag=1
                 this.rules.productName[0].required=true
                 this.rules.productCategory[0].required=true
                this.rules.productStock[0].required=true
                 this.rules.productCustomer[0].required=false
                  this.rules.productBatchNo[0].required=false
            }
            if(val.categoryName=='原材料'){
                this.typeFlag=2
                this.rules.productName[0].required=true
                this.rules.productBatchNo[0].required=false
                 this.rules.productCustomer[0].required=false
                 this.rules.productStock[0].required=true
                 this.rules.productCategory[0].required=false
            }if(val.categoryName=='其他'){
            this.typeFlag=3
             this.rules.productName[0].required=false
               this.rules.productCustomer[0].required=false
               this.rules.productCategory[0].required=false
                this.rules.productStock[0].required=false
                this.rules.productBatchNo[0].required=false
            }
            this.subCategory = null;
            const category = this.category.find(item => item.categoryId == val.categoryId);
            if (category) {
                this.subCategoryList = category.children;
                this.form.productCategory=val.categoryId
            }
            this.productCategoryLabel=val.categoryName
            this.$forceUpdate();
        },

        /**
         * 通过物料编号查询生产所需信息
         */
        checkProduceNeed(row) {
            if (!row.productNo || this.tempInput === row.productNo) {
                return;
            }
            // 存起旧值
            this.tempInput = row.productNo;
            this.tableLoading = true;
            let params={
                productNo:row.productNo,
                type:this.typeFlag
            }
            getProductInfo(params).then(res => {
                if (res.code === responseEnum.success) {
                    row.productName = res.data.productName;
                    row.productNum = res.data.productStock;
                    row.productId = res.data.productId;
                } else {
                    this.resetRow(row);
                   this.$message.error("请输入正确的物料编号");
                }
            }).catch((e) => this.resetRow(row)).finally(() => this.tableLoading = false)
        },

        /**
         * 重置行
         */
        resetRow(row) {
            row.productName = '';
            row.productNum = '';
            row.productId = null;
            this.$nextTick(() => {
                this.$refs.form.clearValidate();
            })
        },

        /**
         * 增行
         */
        onAddRow() {
            const row = _.cloneDeep(this.$options.data().form.needVoList[0]);
            this.form.needVoList.push(row);
        },
        /**
         * 删除行
         */
        onDeleteNeed(index) {
            this.form.needVoList.splice(index, 1)
        },
        /**
         * 提交表单
         */
        submitForm() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    const loading = this.$loading({lock: true});
                    const apiName = this.handleType === handleEnum.add ? 'materialAdd' : 'materialUpdate';
                    if(this.productId){
                         this.form.productId=this.productId
                    }
                    // 分类标识，是否生产所需，如果不是，去掉form.needVoList
                    if (this.typeFlag!='0'&&this.typeFlag!='1') {
                        this.form.needVoList = null;
                    }
                    const data = _.cloneDeep(this.form);
                    data.productCategory = this.subCategory || data.productCategory;
                    Api[apiName](data).then(res => {
                        if (res.code === responseEnum.success) {
                            this.$message.success('保存成功');
                            this.$tab.closeOpenPage();
                            this.$router.back()
                        } else {
                            this.$message.error(res.msg);
                        }
                    }).finally(() => loading.close())
                }
            })
        },
        /*取消、关闭*/
        cancel() {
            this.$tab.closeOpenPage();
            this.$router.back()
        },
    }
}
</script>

<style lang="scss" scoped>
.form-table {
    margin-top: 20px;

    ::v-deep.el-form-item__content {
        line-height: unset;
    }
}

</style>
